<template>
  <div id="app" class="app-container">
    <!-- 游戏加载界面 -->
    <div v-if="isLoading" class="loading-screen">
      <div class="loading-content">
        <div class="loading-logo">
          <div class="logo-icon">🌟</div>
          <h1 class="logo-text">星际帝国</h1>
          <div class="logo-subtitle">Stellar Empire</div>
        </div>
        
        <div class="loading-progress">
          <div class="progress-bar">
            <div 
              class="progress-fill"
              :style="{ width: `${loadingProgress}%` }"
            ></div>
          </div>
          <div class="progress-text">{{ loadingText }}</div>
          <div class="progress-percentage">{{ Math.round(loadingProgress) }}%</div>
        </div>
        
        <div class="loading-tips">
          <div class="tip-text">{{ currentTip }}</div>
        </div>
      </div>
      
      <div class="loading-background">
        <div class="stars"></div>
        <div class="nebula"></div>
      </div>
    </div>

    <!-- 主游戏界面 -->
    <div v-else class="game-interface">
      <!-- 错误边界 -->
      <div v-if="hasError" class="error-boundary">
        <div class="error-content">
          <div class="error-icon">⚠️</div>
          <h2>应用程序遇到错误</h2>
          <p class="error-message">{{ errorMessage }}</p>
          <div class="error-actions">
            <button @click="reloadApp" class="reload-btn">
              重新加载
            </button>
            <button @click="resetApp" class="reset-btn">
              重置应用
            </button>
          </div>
        </div>
      </div>

      <!-- 正常游戏界面 -->
      <GameLayout v-else />
    </div>

    <!-- 全局通知系统 -->
    <NotificationSystem />
    
    <!-- 全局模态框 -->
    <ModalSystem />
    
    <!-- 调试面板 (开发环境) -->
    <DebugPanel v-if="isDevelopment && showDebugPanel" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onErrorCaptured, computed } from 'vue'
import { useRouter } from 'vue-router'
import GameLayout from '@/components/layout/GameLayout.vue'
import NotificationSystem from '@/components/ui/NotificationSystem.vue'
import ModalSystem from '@/components/ui/ModalSystem.vue'
import DebugPanel from '@/components/ui/DebugPanel.vue'
import { useGameStore } from '@/stores'
import { GameEngine } from '@/services'

// 响应式数据
const router = useRouter()
const gameStore = useGameStore()

const isLoading = ref(true)
const loadingProgress = ref(0)
const loadingText = ref('初始化游戏引擎...')
const currentTip = ref('')

const hasError = ref(false)
const errorMessage = ref('')

const showDebugPanel = ref(false)

// 计算属性
const isDevelopment = computed(() => import.meta.env.DEV)

// 加载提示
const loadingTips = [
  '💡 合理规划资源分配，确保帝国稳定发展',
  '🔬 科技是第一生产力，优先发展关键技术',
  '🤝 外交关系影响贸易和军事，谨慎处理',
  '🏗️ 建筑布局影响效率，规划好城市发展',
  '🚀 舰队是帝国的利剑，保持军事优势',
  '🌍 探索未知星系，发现新的资源和机遇',
  '💰 经济是帝国的基础，维持收支平衡',
  '👥 人口是帝国的根本，关注民众需求'
]

// 错误处理
onErrorCaptured((error: Error) => {
  console.error('应用错误:', error)
  hasError.value = true
  errorMessage.value = error.message || '未知错误'
  return false
})

// 应用初始化
async function initializeApp() {
  try {
    // 显示随机提示
    showRandomTip()
    
    // 步骤1: 初始化游戏引擎
    updateLoadingProgress(10, '初始化游戏引擎...')
    await GameEngine.initialize()
    
    // 步骤2: 加载游戏数据
    updateLoadingProgress(30, '加载游戏数据...')
    await gameStore.loadGameData()
    
    // 步骤3: 初始化存储系统
    updateLoadingProgress(50, '初始化存储系统...')
    await gameStore.initializeStores()
    
    // 步骤4: 加载用户设置
    updateLoadingProgress(70, '加载用户设置...')
    await gameStore.loadUserSettings()
    
    // 步骤5: 启动游戏循环
    updateLoadingProgress(85, '启动游戏循环...')
    await GameEngine.startGameLoop()
    
    // 步骤6: 完成初始化
    updateLoadingProgress(100, '初始化完成!')
    
    // 延迟一下显示完成状态
    await new Promise(resolve => setTimeout(resolve, 500))
    
    isLoading.value = false
    
    // 导航到默认页面
    if (router.currentRoute.value.path === '/') {
      await router.push('/overview')
    }
    
  } catch (error) {
    console.error('应用初始化失败:', error)
    hasError.value = true
    errorMessage.value = error instanceof Error ? error.message : '初始化失败'
    isLoading.value = false
  }
}

// 更新加载进度
function updateLoadingProgress(progress: number, text: string) {
  loadingProgress.value = progress
  loadingText.value = text
}

// 显示随机提示
function showRandomTip() {
  const randomIndex = Math.floor(Math.random() * loadingTips.length)
  currentTip.value = loadingTips[randomIndex]
  
  // 每3秒更换一个提示
  const tipInterval = setInterval(() => {
    if (!isLoading.value) {
      clearInterval(tipInterval)
      return
    }
    const newIndex = Math.floor(Math.random() * loadingTips.length)
    currentTip.value = loadingTips[newIndex]
  }, 3000)
}

// 重新加载应用
function reloadApp() {
  window.location.reload()
}

// 重置应用
function resetApp() {
  // 清除本地存储
  localStorage.clear()
  sessionStorage.clear()
  
  // 重新加载页面
  window.location.reload()
}

// 键盘快捷键
function handleKeydown(event: KeyboardEvent) {
  // 开发环境快捷键
  if (isDevelopment.value) {
    // F12 或 Ctrl+Shift+D 打开调试面板
    if (event.key === 'F12' || (event.ctrlKey && event.shiftKey && event.key === 'D')) {
      event.preventDefault()
      showDebugPanel.value = !showDebugPanel.value
    }
  }
  
  // 游戏快捷键
  if (!isLoading.value && !hasError.value) {
    // 空格键暂停/继续游戏
    if (event.code === 'Space' && !event.ctrlKey && !event.altKey) {
      event.preventDefault()
      gameStore.togglePause()
    }
    
    // 数字键快速导航
    const numKey = parseInt(event.key)
    if (numKey >= 1 && numKey <= 9 && !event.ctrlKey && !event.altKey) {
      const routes = [
        '/overview',    // 1
        '/resources',   // 2
        '/buildings',   // 3
        '/technology',  // 4
        '/ships',       // 5
        '/diplomacy',   // 6
        '/galaxy',      // 7
        '/colonies',    // 8
        '/settings'     // 9
      ]
      
      const targetRoute = routes[numKey - 1]
      if (targetRoute && router.currentRoute.value.path !== targetRoute) {
        router.push(targetRoute)
      }
    }
  }
}

// 生命周期
onMounted(async () => {
  // 添加键盘事件监听
  window.addEventListener('keydown', handleKeydown)
  
  // 添加错误处理
  window.addEventListener('error', (event) => {
    console.error('全局错误:', event.error)
    hasError.value = true
    errorMessage.value = event.error?.message || '未知错误'
  })
  
  window.addEventListener('unhandledrejection', (event) => {
    console.error('未处理的Promise拒绝:', event.reason)
    hasError.value = true
    errorMessage.value = event.reason?.message || '异步操作失败'
  })
  
  // 初始化应用
  await initializeApp()
})

// 清理
function cleanup() {
  window.removeEventListener('keydown', handleKeydown)
}

// 组件卸载时清理
import { onBeforeUnmount } from 'vue'
onBeforeUnmount(() => {
  cleanup()
})
</script>

<style scoped>
.app-container {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: #0a0a0f;
  color: #ffffff;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 加载界面样式 */
.loading-screen {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #0a0a0f 0%, #1a1a2e 50%, #16213e 100%);
  overflow: hidden;
}

.loading-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.stars {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: 
    radial-gradient(2px 2px at 20px 30px, #ffffff, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255, 255, 255, 0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #ffffff, transparent),
    radial-gradient(1px 1px at 130px 80px, rgba(255, 255, 255, 0.6), transparent),
    radial-gradient(2px 2px at 160px 30px, #ffffff, transparent);
  background-repeat: repeat;
  background-size: 200px 100px;
  animation: twinkle 4s ease-in-out infinite alternate;
}

.nebula {
  position: absolute;
  width: 100%;
  height: 100%;
  background: radial-gradient(ellipse at center, rgba(0, 212, 255, 0.1) 0%, transparent 70%);
  animation: nebula-drift 20s ease-in-out infinite alternate;
}

@keyframes twinkle {
  0% { opacity: 0.3; }
  100% { opacity: 1; }
}

@keyframes nebula-drift {
  0% { transform: translateX(-10px) translateY(-5px); }
  100% { transform: translateX(10px) translateY(5px); }
}

.loading-content {
  position: relative;
  z-index: 2;
  text-align: center;
  max-width: 500px;
  padding: 2rem;
}

.loading-logo {
  margin-bottom: 3rem;
}

.logo-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
  animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.1); opacity: 0.8; }
}

.logo-text {
  font-size: 2.5rem;
  font-weight: 700;
  margin: 0 0 0.5rem 0;
  background: linear-gradient(135deg, #00d4ff, #ffffff, #00ff88);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 0 20px rgba(0, 212, 255, 0.5);
}

.logo-subtitle {
  font-size: 1.2rem;
  color: #cccccc;
  font-weight: 300;
  letter-spacing: 2px;
}

.loading-progress {
  margin-bottom: 2rem;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 1rem;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #00d4ff, #00ff88);
  border-radius: 4px;
  transition: width 0.3s ease;
  box-shadow: 0 0 10px rgba(0, 212, 255, 0.5);
}

.progress-text {
  font-size: 1rem;
  color: #ffffff;
  margin-bottom: 0.5rem;
}

.progress-percentage {
  font-size: 1.2rem;
  font-weight: 600;
  color: #00d4ff;
}

.loading-tips {
  padding: 1rem;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.tip-text {
  font-size: 0.95rem;
  color: #cccccc;
  line-height: 1.5;
  min-height: 1.5em;
  animation: fade-in 0.5s ease-in-out;
}

@keyframes fade-in {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

/* 游戏界面样式 */
.game-interface {
  width: 100%;
  height: 100%;
}

/* 错误边界样式 */
.error-boundary {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #1a0a0a, #2a1a1a);
}

.error-content {
  text-align: center;
  max-width: 500px;
  padding: 2rem;
  background: rgba(0, 0, 0, 0.6);
  border: 1px solid rgba(255, 107, 107, 0.3);
  border-radius: 12px;
}

.error-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
}

.error-content h2 {
  color: #ff6b6b;
  margin-bottom: 1rem;
  font-size: 1.5rem;
}

.error-message {
  color: #cccccc;
  margin-bottom: 2rem;
  line-height: 1.5;
}

.error-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.reload-btn,
.reset-btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.reload-btn {
  background: linear-gradient(135deg, #00d4ff, #0099cc);
  color: #000000;
}

.reload-btn:hover {
  background: linear-gradient(135deg, #0099cc, #007399);
  transform: translateY(-1px);
}

.reset-btn {
  background: linear-gradient(135deg, #ff6b6b, #ef4444);
  color: #ffffff;
}

.reset-btn:hover {
  background: linear-gradient(135deg, #ef4444, #dc2626);
  transform: translateY(-1px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .loading-content {
    padding: 1rem;
    max-width: 90%;
  }
  
  .logo-text {
    font-size: 2rem;
  }
  
  .logo-subtitle {
    font-size: 1rem;
  }
  
  .error-actions {
    flex-direction: column;
  }
}

@media (max-width: 480px) {
  .logo-text {
    font-size: 1.5rem;
  }
  
  .logo-icon {
    font-size: 3rem;
  }
  
  .tip-text {
    font-size: 0.875rem;
  }
}
</style>